<template>
  <div style="display: inline-block">
    <el-upload
               :action="action||uploadUrl"
               :show-file-list="false"
               :name="name"
               :data="data"
               :accept="accept"
               :headers="headers"
               :on-success="handleSuccess"
               :before-upload="beforeUpload"
               :on-progress="handleProgress"
               :on-error="handleError"
    >
      <el-button type="primary" :size="btnSize" icon="el-icon-upload">上传</el-button>
    </el-upload>
    <div v-if="loading" class="el-loading-mask" style="width:100%;height:100%;position:fixed;">
      <div class="el-loading-spinner" style="transform:translate(-40px,-20px);">
        <el-progress type="circle" :percentage="percentage"></el-progress>
        <p class="el-loading-text">上传中...</p></div>
    </div>
  </div>
</template>

<script>
  import config from '../../config'
  import {getCookie} from '../../libs/cookie'

  export default {
    name: 'es-upload-file',
    props: {
      action: String,//上传地址
      accept:String,
      data:Object,//附带参数
      name: String,
      btnSize:String,
      size: Number//单个文件最大大小
    },
    data: function () {
      return {
        uploadUrl: config.uploadUrl,
        sizeLimit: 0,
        headers: {token: getCookie('token')},
        loading:false,
        percentage: 0,
      }
    },
    mounted: function () {
      this.sizeLimit = this.size ? this.size : 100;
    },
    methods: {
      //上传成功
      handleSuccess(res, file) {
        let _this = this;
        if (res.code === 200) {
          if (this.currentIndex === this.uploadNum) {
            this.percentage = 95;
            let time = setInterval(function () {
              _this.percentage++;
              if (_this.percentage >= 100) {
                _this.loading = false;
                _this.percentage = 0;
                clearTimeout(time);
                _this.$message.success('上传成功');
                _this.$emit('uploadSuccess', res.data);
              }
            }, 300)
          }
        } else {
          _this.loading = false;
          _this.percentage = 0;
          this.$message.error(res.msg);
        }
      },
      beforeUpload(file) {
        // 文件大小限制
        const sizeLimit = file.size / 1024 / 1024 < this.sizeLimit;
        if (!sizeLimit) {
          this.$message.error('上传的文件大小不能超过 ' + this.sizeLimit + 'MB!')
        }
        return sizeLimit
      },
      handleProgress(event, file, fileList) {
        let _this = this;
        _this.loading = true;
        let time = setInterval(function () {
          _this.percentage++;
          if (_this.percentage === 95 || !_this.loading) {
            clearTimeout(time)
          }
        }, 1000)

      },
      handleError() {
        this.$message.error("上传失败");
        this.loading = false
      }
    }
  }
</script>

<style scoped>

</style>
